package com.longchat.query;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.longchat.domain.award.Questionnaire;
import com.longchat.dto.comm.DatatablesPageViewInfo;
import com.longchat.dto.vote.VoteDataTablesQueryInfo;

@Component
public class VoteQuery {
	@PersistenceContext
	private EntityManager entityManager;
	public DatatablesPageViewInfo<Questionnaire> findPageBy(VoteDataTablesQueryInfo info){
		
		StringBuffer sql = new StringBuffer("SELECT * FROM questionnaire q where 1=1");
		if(StringUtils.isNotEmpty(info.getName())){
			sql.append(" AND q.name=:name");
		}
		if(info.getType()!=null){
			sql.append(" AND q.type=:type");
		}
		sql.append(" limit :start,:length");
		Query query = entityManager.createNativeQuery(sql.toString(),Questionnaire.class);
		if(StringUtils.isNotEmpty(info.getName())){
			query.setParameter("name", info.getName());
		}
		if(info.getType()!=null){
			query.setParameter("type", info.getType());
		}
		query.setParameter("start", info.getStart());
		query.setParameter("length", info.getLength());
		//count
		StringBuffer countSql = new StringBuffer("SELECT count(1) from questionnaire q where 1=1");
		if(StringUtils.isNotEmpty(info.getName())){
			countSql.append(" AND q.name=:name");
		}
		if(info.getType()!=null){
			countSql.append(" AND q.type=:type");
		}
		Query countQuery = entityManager.createNativeQuery(countSql.toString());
		if(StringUtils.isNotEmpty(info.getName())){
			countQuery.setParameter("name", info.getName());
		}
		if(info.getType()!=null){
			countQuery.setParameter("type", info.getType());
		}
		int count = Integer.parseInt(countQuery.getSingleResult().toString());
		DatatablesPageViewInfo<Questionnaire> tables = new DatatablesPageViewInfo<Questionnaire>();
		tables.setData(query.getResultList());
		tables.setRecordsTotal(count);
		tables.setRecordsFiltered(count);
		return tables;
		
		
	}
}
